<?php
include('database.php');
include('foody.class.php');
include('notify.class.php');

$foody = new foody();
$grouplist = getGroupList();
foreach($grouplist as $group) {
    //$url = 'http://widget.foody.vn/review/reviews?rid=35140&rcount=10';

    $url = 'http://www.foody.vn/'. $group['location'] .'/'. $group['name'] .'/binh-luan';
    $content = $foody->getReviews($url);

    if(empty($content))  {
        echo "Content empty";exit;
    }

    $reviewList = $foody->parseDataWeb($content);
    echo "<pre>";
    print_r($reviewList);
    echo "</pre>";

    $result = insertData($reviewList, $group['group_id']);
    if($result) {
        //sendNotification($group['user_id'];
    }
}

function sendNotification($userId)
{
    $newCommentId = mysql_insert_id();
    if(intval($newCommentId)) {
    
        //get and cut new comment string
        $commentNotify = getNewComment($newCommentId);
        $deviceToken = getDeviceToken($userId);
        
        $notify = new notify();
        $notify->_deviceToken = $deviceToken;
        if($notify->send($commentNotify)) {
            echo 'Sent notification';exit;
        }
        
        //Error, alert to email to see function send notify
        //Write log file
        //echo 'Don\'t sent notification';exit;
    }
    
    //Write log file
    echo "Successful, have no a new comment";exit;
}

function getDeviceToken($userId)
{
    $query = 'SELECT * FROM `cp_users` WHERE status = 1 AND user_id =' . $userId;
    $result = mysql_query($query);

    if (!$result) {
        //Error, alert to email to see query
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        return false;
    }

    $data = mysql_fetch_assoc($result);
    return $data['token'];
}

/**
* Insert data comment 
* @param array $reviewList is list data comment
* @return boolean true|false
*/
function insertData($reviewList, $groupId) 
{
    $count = count($reviewList);
    if($count) {
        $sql = "INSERT IGNORE INTO  `group_foody_comment`(`group_id`, `image`, `description`, `user`, `username`, `time`, `date_comment`, `point`, `created`) VALUES";

        foreach($reviewList as $key=>$review) {

            $dateArr = explode('-', $review['time']);
            $dateComment = str_replace('/', '-', trim($dateArr[0]));
            
            $sql .= "($groupId,";
            $sql .= "'". $review['image'] ."',";
            $sql .= "'". html_entity_decode($review['description']) ."',";
            $sql .= "'". $review['user'] ."',";
            $sql .= "'". html_entity_decode($review['username']) ."',";
            $sql .= "'". strtotime($dateComment) ."',";
            $sql .= "'". $review['time'] ."',";
            $sql .= "'". $review['point'] ."',";
            $sql .= "'". date('Y-m-d H:i:s') ."'";
            if($key == ($count -1)) $sql .= ");";
            else $sql .= "),";
        }
    }
    
    //echo $sql;exit;
    $result = mysql_query($sql);

    if (!$result) {
        //Error, alert to email to see function insert
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        return false;
    }
    
    return true;
}

/**
* Get new comment by comment id
* @param int $id is id of comment
* @return string $comment is a text
*/
function getNewComment($id) 
{
    $query = 'SELECT * FROM `group_foody_comment` WHERE point <= 6 AND id >=' . $id;
    $result = mysql_query($query);
    $data = array();
    if ($result) {
        $data = mysql_fetch_assoc($result);
    } else {
        //Error, alert to email to see query
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        return false;
    }

    $comment = string_trim($data['description']);
    return $comment;
}

function getGroupList() 
{
    $query = 'SELECT * FROM `group_foody`';
    $result = mysql_query($query);
    
    if (!$result) {
        //Error, alert to email to see query
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        return false;
    }
    
    $i=0;
    $data = array();
    while ($row = mysql_fetch_assoc($result)) {
        $data[$i] = $row;
        $i++;
    }

    mysql_free_result($result);
    
    return $data;
}

function string_trim($string, $trimLength = 80) 
{
    $length = strlen($string);
    if ($length > $trimLength) {
        $count = 0;
        $prevCount = 0;
        $array = explode(" ", $string);
        foreach ($array as $word) {
            $count = $count + strlen($word);
            $count = $count + 1;
            if ($count > ($trimLength - 3)) {
                return substr($string, 0, $prevCount) . "...";
            }
            $prevCount = $count;
        }
    } else {
        return $string;
    }
}